#include "mpctrl.h"
#include "CTNull.h"

#ifdef _DEBUG
#define THIS_BUILD "debug"
#else
#define THIS_BUILD "release"
#endif

int g_iSvrPid = 0;

void PrintVersion()
{
    printf("huochao qqgame %s %s %s version build at %s %s\n",
        APPNAME, 
#ifdef  THIS_VERSION
        THIS_VERSION
#else
        "unknown"
#endif
        , THIS_BUILD, __DATE__, __TIME__);
}

void PrintUsage()
{
    PrintVersion();
    printf("Usage: %s [options]\n", APPNAME);
    printf("\nOptions:\n");
    printf("%-8s run program not daemon\n", "-g");
    printf("%-8s show help\n", "-h");
    printf("%-8s show version\n", "-v");
    printf("\nCommands:\n");
    printf("kill -s USR1 <pid> \t notify %s reload config\n", APPNAME);
    printf("kill -s USR2 <pid> \t notify %s exit\n", APPNAME);
}

void AtExit()
{
    if (getpid() != g_iSvrPid)
    {
        return;
    }
    CTServerUtils::RemovePidFile(APPNAME);
}

int main(int argc, char** argv)
{
    bool bDaemon = true;	// 默认后台执行

    int iOpt = 0;
    while ((iOpt = getopt(argc, argv, "vgh")) != -1)
    {
        switch(iOpt)
        {
        case 'v':
            PrintVersion();
            return 0;

        case 'g':
            bDaemon = false;
            break;

        case 'h':
        default:
            PrintUsage();
            return 0;
        }
    }

    // 后台运行
    if (bDaemon)
    {
        CTServerUtils::InitDaemon();
    }

    // 避免启动多个进程
    if (!CTServerUtils::CheckSingleRun(argv[0]))
    {
        return -1;
    }

    g_iSvrPid = getpid();
    // 退出时自动清理
    atexit(AtExit);

    try
    {
        CMpCtrl ctrl;
        ctrl.Init();
        ctrl.Run();
        ctrl.Exit();
    }
    catch (CTException& CT_UNUSED(e))
    {
        return -1;
    }

    return 0;
}
